<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  getOrderMessageService,
  getUserNameService,
  getRoomNameService,
  delorderMessageService,
  delPaymentsMessageService,
} from '@/api/order'
import { formatTime } from '@/utils/format'
import { Delete } from '@element-plus/icons-vue'
const loading = ref(false)
const total = ref(0) // 总条数
const orderList = ref([])
const paymentStatus = ref('') //搜索框的值：支付状态
const orderStatus = ref('') //搜索框的值：订单状态
const NameList = ref([]) //用户名列表  //房间名列表

const paymentStatusList = ref([
  { id: '未支付', value: 'pending' },
  { id: '已支付', value: 'paid' },
  { id: '支付失败', value: 'failed' },
  { id: '取消支付', value: 'cancelled' },
  { id: '无', value: '' },
])
const orderStatusList = ref([
  { id: '未完成', value: 'pending' },
  { id: '已确定', value: 'confirmed' },
  { id: '已完成', value: 'completed' },
  { id: '已评价', value: 'commented' },
  { id: '取消订单', value: 'cancelled' },
  { id: '无', value: '' },
])

const goSearch = () => {
  // 获取选中的支付状态和订单状态
  console.log('支付状态:', paymentStatus.value)
  console.log('订单状态:', orderStatus.value)
  getOrderMessage(paymentStatus.value, orderStatus.value)
}
const getOrderMessage = async (a, b) => {
  loading.value = true
  const res = await getOrderMessageService({ payment_status: a, order_status: b })
  orderList.value = res.data.data
  total.value = res.data.data.length
  loading.value = false
  // 获取每一行的用户名和房间名
  await updateNameList()
}
// 使用 watch 来监听 orderList 的变化，确保 NameList 数据更新完毕后才渲染
watch(orderList, async (newOrderList) => {
  if (newOrderList.length > 0) {
    await updateNameList() // 数据更新完毕后更新 NameList
  }
})
// 更新 NameList 的函数
const updateNameList = async () => {
  NameList.value = []

  for (let i = 0; i < orderList.value.length; i++) {
    const userId = orderList.value[i].user_id
    const roomId = orderList.value[i].room_id
    const orderId = orderList.value[i].order_id
    const userName = await getUserName(userId) // 获取用户名
    const roomName = await getRoomName(roomId) // 获取房间名
    // 更新 NameList
    NameList.value.push({
      order_id: orderId,
      room_name: roomName,
      user_name: userName,
    })
  }
}

onMounted(async () => {
  getOrderMessage(paymentStatus.value, orderStatus.value)
})

// 获取用户名的异步函数
const getUserName = async (userId) => {
  // 否则发起异步请求获取用户名
  const res = await getUserNameService(userId)
  return res.data.data[0].full_name
}

const getRoomName = async (roomId) => {
  const res = await getRoomNameService(roomId)
  return res.data.data[0].room_name
}
// 根据 orderId 查找对应的 user_name
const fff = (orderId) => {
  const res = NameList.value.find((r) => r.order_id === orderId)
  return res ? res.user_name : '未知' // 如果找不到用户姓名，返回 '未知'
}
const ggg = (orderId) => {
  const res = NameList.value.find((r) => r.order_id === orderId)
  return res ? res.room_name : '未知' // 如果找不到用户姓名，返回 '未知'
}

// 删除房间列表信息
const onDelChannel = async (row) => {
  console.log(row)
  await ElMessageBox.confirm('你确认删除该条数据吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
  await delPaymentsMessageService(row.order_id)
  await delorderMessageService(row.order_id)
  ElMessage({ type: 'success', message: '删除成功' })
  getOrderMessage(paymentStatus.value, orderStatus.value)
}
//分页
const currentPage = ref(1) // 当前页
const pagesize = ref(5) // 每页条数
// pagesize每页条数 改变时触发
const onSizeChange = (size) => {
  currentPage.value = 1
  pagesize.value = size
}
// 分页数据计算属性
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pagesize.value
  const end = start + pagesize.value
  return orderList.value.slice(start, end)
})

// currentPage 当前页 改变时触发
const onCurrentChange = (page) => {
  currentPage.value = page
}
</script>
<template>
  <page-container title="订单管理">
    <template #extra>
      <div style="display: flex">
        <el-select
          v-model="paymentStatus"
          style="width: 200px; margin: 0 20px"
          placeholder="请选择支付状态"
        >
          <el-option
            v-for="item in paymentStatusList"
            :key="item.value"
            :label="item.id"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="orderStatus"
          style="width: 200px; margin: 0 20px"
          placeholder="请选择订单状态"
        >
          <el-option
            v-for="item in orderStatusList"
            :key="item.value"
            :label="item.id"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="goSearch">搜索</el-button>
      </div>
    </template>

    <el-table :data="paginatedData" v-loading="loading" style="width: 100%; margin-top: 20px">
      <el-table-column label="序号" align="center" width="80">
        <template #default="{ $index }">
          <!-- 当前页的索引加上偏移量来计算序号 -->
          {{ $index + 1 + (currentPage - 1) * pagesize }}
        </template>
      </el-table-column>
      <el-table-column label="订单ID" prop="order_id" align="center" width="80"></el-table-column>
      <el-table-column label="顾客姓名" align="center">
        <template #default="{ row }">
          {{ fff(row.order_id) }}
        </template>
      </el-table-column>
      <el-table-column label="房间名称" align="center">
        <template #default="{ row }">
          {{ ggg(row.order_id) }}
        </template>
      </el-table-column>
      <el-table-column label="入住日期" align="center">
        <template #default="{ row }">
          {{ formatTime(row.check_in_date) }}
        </template>
      </el-table-column>
      <el-table-column label="退房日期" prop="check_out_date" align="center">
        <template #default="{ row }">
          {{ formatTime(row.check_out_date) }}
        </template>
      </el-table-column>
      <el-table-column label="金额" prop="total_price" align="center"></el-table-column>
      <el-table-column label="支付状态" prop="payment_status" align="center">
        <template #default="{ row }">
          <span v-if="row.payment_status === 'pending'">未支付</span>
          <span v-else-if="row.payment_status === 'paid'">已支付</span>
          <span v-else-if="row.payment_status === 'failed'">支付失败</span>
          <span v-else-if="row.payment_status === 'cancelled'">取消支付</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="order_status" align="center">
        <template #default="{ row }">
          <span v-if="row.order_status === 'pending'">未完成</span>
          <span v-else-if="row.order_status === 'confirmed'">已确定</span>
          <span v-else-if="row.order_status === 'completed'">已完成</span>
          <span v-else-if="row.order_status === 'commented'">已评价</span>
          <span v-else-if="row.order_status === 'cancelled'">取消订单</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <!-- row 就是 channelList 的一项，类似于item； $index 下标 -->
        <template #default="{ row }">
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="onDelChannel(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pagesize"
      :page-sizes="[2, 3, 4, 5, 10]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
</template>
<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 150px;
      height: 130px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
